package yams.resource.impl;

import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Maps;
import javafx.util.Callback;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import yams.callback.IdCallback;
import yams.common.InfoPage;
import yams.common.constants.Constants;
import yams.domain.*;
import yams.resource.ICheckmeterResource;
import yams.resource.JsonCommonResource;
import yams.response.JsonResponse;
import yams.service.*;
import yams.service.impl.DefaultCommonService;
import yams.utils.SystemTool;

import javax.annotation.Resource;
import java.io.IOException;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;
import java.util.TreeMap;

/**
 * 抄表管理对外服务
 * Created by Luffy on 2017/06/13.
 */
@SuppressWarnings("unchecked")
@RestController
@RequestMapping("/checkmeter")
public class DefaultCheckmeterResource extends JsonCommonResource implements ICheckmeterResource {

    @Resource
    private IWeChatService weChatService;
    @Resource
    private ICheckmeterService checkmeterService;
    @Resource
    private IHouseService houseService;
    @Resource
    private IBillService billService;
    @Resource
    private IContractService contractService;
    @Resource
    private IUserService userService;
    @Resource
    private IApartmentService apartmentService;

    private ICommonService enumService;

    @Autowired
    private IdCallback idCallback;

    /**
     * 抄表查询 列表展示
     *
     * @param checkmeterEntity
     * @return
     */
    @RequestMapping(value = "/query", method = RequestMethod.POST)
    @Override
    public JsonResponse<CheckmeterEntity> query(@RequestBody CheckmeterEntity checkmeterEntity) {

        InfoPage<CheckmeterEntity> page;
        //filterFlag标识用来区分是普通查询，还是查询未抄表的数据
        //1
        String filt = checkmeterEntity.getProperties().get("filterFlag").toString();
        if (filt != null && ("1").equals(filt)) {
            page = checkmeterService.filterCheckmeter(checkmeterEntity);
        }
        //0
        else {
            page = checkmeterService.queryCheckmeter(checkmeterEntity);
            page.getContent().forEach(a -> {
                if (a.getCode() == null)
                    a.setCode(a.getHouseId() + "_" + a.getMeterYear() + a.getMeterMonth());
            });
        }
        return JsonResponse.build(page);

    }


    @RequestMapping(value = "/", method = RequestMethod.POST)
    @Override
    public JsonResponse<CheckmeterEntity> page(@RequestBody CheckmeterEntity checkmeterEntity) {
        return _pageAll(checkmeterService, checkmeterEntity);
    }

    @RequestMapping(value = "/{id}", method = RequestMethod.GET)
    @Override
    public JsonResponse<CheckmeterEntity> findById(@PathVariable String id) {
        return _findOne(checkmeterService, id, 0);
    }

    @RequestMapping(value = "/code/{code}", method = RequestMethod.GET)
    @Override
    public JsonResponse<CheckmeterEntity> findByCode(@PathVariable String code) {
        return _findOne(checkmeterService, code, 1);
    }

    /**
     * 保存
     *
     * @param checkmeterEntity
     * @return
     */
    @RequestMapping(value = "/", method = RequestMethod.PUT)
    @Override
    public JsonResponse<CheckmeterEntity> save(@RequestBody CheckmeterEntity checkmeterEntity) {
        CheckmeterEntity old = checkmeterService.findByCode(checkmeterEntity.getCode());
        if (old != null) {
            if (checkmeterEntity.getElectric() != null)
                old.setElectric(checkmeterEntity.getElectric());
            if (checkmeterEntity.getGas() != null)
                old.setGas(checkmeterEntity.getGas());
            if (checkmeterEntity.getWater() != null)
                old.setWater(checkmeterEntity.getWater());
            checkmeterService.saveInfo(old);
        } else {
            HouseEntity houseEntity = houseService.findById(checkmeterEntity.getHouseId());
            if (houseEntity != null) {
                checkmeterEntity.setHouse(houseEntity);
                checkmeterEntity.setName(houseEntity.getName() + checkmeterEntity.getMeterMonth());
            }
            _saveInfo(checkmeterService,checkmeterEntity);
        }
        return JsonResponse.OK();
    }

    /**
     * 生成水电费账单
     *
     * @param checkmeterEntity
     * @return
     */
    @RequestMapping(value = "/generateBill", method = RequestMethod.PUT)
    @Override
    public JsonResponse<CheckmeterEntity> generateBill(@RequestBody CheckmeterEntity checkmeterEntity) {
        CheckmeterEntity currentCheckmeterEntity =null;
        if(checkmeterEntity.getId()==null && checkmeterEntity.getCode()!=null){
            currentCheckmeterEntity=checkmeterService.findByCode(checkmeterEntity.getCode());
        }else{
            currentCheckmeterEntity = checkmeterService.findById(checkmeterEntity.getId());
        }
        HouseEntity houseEntity = houseService.findById(currentCheckmeterEntity.getHouse().getId());
        UserEntity manager = userService.findById(houseEntity.getManager());
        ContractEntity contractEntity = contractService.findById(houseEntity.getContract().getId());
        UserEntity user = contractEntity.getUser();

        CheckmeterEntity queryLastDataCondition = new CheckmeterEntity();
        int currentMonth = Integer.parseInt(currentCheckmeterEntity.getMeterMonth());
        if (currentMonth == 1) {//如果本月是1月，那上次日期就是去年12月份
            queryLastDataCondition.getProperties().put("meterYear", String.valueOf(Integer.parseInt(currentCheckmeterEntity.getMeterYear()) - 1));
            queryLastDataCondition.getProperties().put("meterMonth", 12);
        } else {
            queryLastDataCondition.getProperties().put("meterYear", currentCheckmeterEntity.getMeterYear());
            queryLastDataCondition.getProperties().put("meterMonth", String.valueOf(currentMonth - 1));
        }
        queryLastDataCondition.getProperties().put("house_id_obj_ae", currentCheckmeterEntity.getHouseId());
        List<CheckmeterEntity> lastList = checkmeterService.listAll(queryLastDataCondition);
        CheckmeterEntity lastCheckmeterEntity = new CheckmeterEntity();
        if (lastList != null && lastList.size() > 0) {
            lastCheckmeterEntity = lastList.get(0);
        }

        BillEntity billEntity = new BillEntity();

        billEntity.setType(2);
        BigDecimal total = new BigDecimal(0);
        billEntity.setUser(contractEntity.getUser());
        billEntity.setHouse(houseEntity);
        billEntity.setContract(contractEntity);
        LocalDate ld = LocalDate.now();
        billEntity.setCode("2" + contractEntity.getCode() + "-" + ld.toString().replace("-", ""));
        billEntity.setName(contractEntity.getHouseName() + ld.toString() + "水电气账单");
        //获取单价(现在是每一幢楼的水电单价不同了,水电费现在是按照每一幢楼的规定收取费用)
        ApartmentEntity apartmentEntity=apartmentService.findById(houseEntity.getApartmentId());
        billEntity.setWaterPrice(apartmentEntity.getWaterUnitPrice());
        billEntity.setElectricPrice(apartmentEntity.getElectricUnitPrice());
        EnumEntity ee = (EnumEntity) _findOne(enumService, "systemConfig", 1).getValue();
        for (EnumItemEntity a : ee.getItems()) {
            if (a.getCode().equals("gas")) {
                billEntity.setGasPrice(new BigDecimal(a.getName()));
            }
        }
        billEntity.setWaterNum(new BigDecimal(currentCheckmeterEntity.getWater() == null ? 0 : Integer.valueOf(currentCheckmeterEntity.getWater())));
        billEntity.setPreWater(new BigDecimal(lastCheckmeterEntity.getWater() ==  null ? 0 : Integer.valueOf(lastCheckmeterEntity.getWater())));
        billEntity.setGasNum(new BigDecimal(currentCheckmeterEntity.getGas()==  null ? 0 : Integer.valueOf(currentCheckmeterEntity.getGas())));
        billEntity.setPreGas(new BigDecimal(lastCheckmeterEntity.getGas()==  null ? 0 : Integer.valueOf(lastCheckmeterEntity.getGas())));
        billEntity.setElectricNum(new BigDecimal(currentCheckmeterEntity.getElectric()==  null ? 0 : Integer.valueOf(currentCheckmeterEntity.getElectric())));
        billEntity.setPreElectric(new BigDecimal(lastCheckmeterEntity.getElectric()==  null ? 0 : Integer.valueOf(lastCheckmeterEntity.getElectric())));

        if (billEntity.getWaterNum() != null) {
            billEntity.water();
            total = total.add(billEntity.getWaterAmount());
            contractEntity.setWater(billEntity.getWaterNum().doubleValue());
        }
        if (billEntity.getElectricNum() != null) {
            billEntity.electric();
            total = total.add(billEntity.getElectricAmount());
            contractEntity.setElectric(billEntity.getElectricNum().doubleValue());
        }
        if (billEntity.getGasNum() != null) {
            billEntity.gas();
            total = total.add(billEntity.getGasAmount());
            contractEntity.setGas(billEntity.getGasNum().doubleValue());
        }

        billEntity.setStatus(0);
        billEntity.setTotalAmount(total);
        if (billEntity.getDiscount() != null) {
            billEntity.setActualAmount(billEntity.getTotalAmount().multiply(billEntity.getDiscount()));
        } else {
            billEntity.setActualAmount(billEntity.getTotalAmount());
        }
        billService.getRepository().saveEntity(billEntity, new Callback[]{idCallback});
//        billService.saveInfo(billEntity,new Callback[]{idCallback});
        contractService.getRepository().saveEntity(contractEntity);

        currentCheckmeterEntity.setIsGenBill("Y");

        //给客户发送账单消息
        WechatTemplateMsg templateMsg = new WechatTemplateMsg();
        templateMsg.setTouser(user.getWeChat());
        templateMsg.setTemplate_id("8TBpNPfFKp8OEOVQqXHsPEcXHUvQuGjTZa9HKQuePqM");
        templateMsg.setUrl("http://"+ Constants.WECHAT_URL+"/yams/view/account?openId=" + user.getWeChat());
        TreeMap<String, TreeMap<String, String>> map = Maps.newTreeMap();
//        酒店名称：{{keyword1.DATA}}
//        入住时间：{{keyword2.DATA}}
//        退房时间：{{keyword3.DATA}}
//        订单金额：{{keyword4.DATA}}
//        订单类型：{{keyword5.DATA}}
        map.put("first", templateMsg.item("尊敬的客户，您好！您的新账单已出(水费:" + billEntity.getWaterAmount() + ",电费:" + billEntity.getElectricAmount() + ",煤气费:" + billEntity.getGasAmount() + ")，请在12小时内完成支付", "#173177"));
        map.put("keyword1", templateMsg.item(houseEntity.getApartmentName() + "(房间号:" + houseEntity.getHouseNumber() + ")", ""));
        map.put("keyword2", templateMsg.item(SystemTool.dateToString(contractEntity.getStartDate(),
                "yyyy-MM-dd HH:mm:ss"), ""));
        map.put("keyword3", templateMsg.item(SystemTool.dateToString(contractEntity.getEndDate(),
                "yyyy-MM-dd HH:mm:ss"), ""));
        map.put("keyword4", templateMsg.item(total.toString() + "元", ""));
        map.put("keyword5", templateMsg.item("水电气", ""));
        map.put("remark", templateMsg.item("若有疑问请与管理员(" + manager.getName() + "," + manager.getPhone() + ")联系", "#173177"));
        templateMsg.setData(map);
        String jsonTempl = JSONObject.toJSONString(templateMsg);

        try {
            weChatService.sendTemplate(jsonTempl);
        } catch (IOException e) {
            e.printStackTrace();
        }

        return _saveInfo(checkmeterService, currentCheckmeterEntity);
    }

    @RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
    @Override
    public JsonResponse<CheckmeterEntity> delete(@PathVariable String id) {
        return _delete(checkmeterService, id);
    }

    @Override
    public void initService() {
        if (enumService == null)
            enumService = new DefaultCommonService("enumRepository");

    }
}
